package com.costaccounting.web.controller.report;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.costaccounting.base.service.IZsItemService;
import com.costaccounting.common.core.domain.entity.SysUser;
import com.costaccounting.common.utils.ItemUtil;
import com.costaccounting.common.utils.SecurityUtils;
import com.costaccounting.report.domain.ReportLineVo;
import com.costaccounting.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.costaccounting.common.annotation.Log;
import com.costaccounting.common.core.controller.BaseController;
import com.costaccounting.common.core.domain.AjaxResult;
import com.costaccounting.common.enums.BusinessType;
import com.costaccounting.report.domain.ZsItemReport;
import com.costaccounting.report.service.IZsItemReportService;
import com.costaccounting.common.utils.poi.ExcelUtil;
import com.costaccounting.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 项目经济运行分析Controller
 *
 * @author ruoyi
 * @date 2021-12-07
 */
@RestController
@RequestMapping("/report/itemReport")
public class ZsItemReportController extends BaseController {
    @Autowired
    private IZsItemReportService zsItemReportService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IZsItemService itemService;

    /**
     * 查询统计所需数据
     */
    @GetMapping("/getReportLine")
    public AjaxResult getReportLine(ReportLineVo reportLineVo) throws Exception {
        HashMap<String, Object> mmap = new HashMap<>();
        List<Long> itemIds = reportLineVo.getItemId();
        List<String> month = reportLineVo.getMonth();
        List<String> monthList = new ArrayList<>();
        for (String s : month) {
            monthList.add(s + "月");
        }
        mmap.put("monthList", monthList);
        //多项目
        if (1 < itemIds.size()) {
            String year = reportLineVo.getYear();

            ZsItemReport itemReport = new ZsItemReport();
//            itemReport.setItemId(itemIds.get(0));
            itemReport.setItemIdList(itemIds);
            itemReport.setYear(year);
            itemReport.setMonthList(month);
            List<ZsItemReport> list = zsItemReportService.selectZsItemReportList(itemReport);
            ItemUtil<ZsItemReport> util = new ItemUtil<ZsItemReport>(ZsItemReport.class);
            Map<Long, List<ZsItemReport>> irMap = list.stream().collect(Collectors.groupingBy(ZsItemReport::getItemId));
            List<String> fieldList = reportLineVo.getFieldList();

            //柱状图数据
//        Map<String,List<BigDecimal>> rMap=new HashMap<>();
            Map rMap = new LinkedHashMap();
            //项目列表
            long[] items = new long[itemIds.size()];
            for (int i = 0; i < itemIds.size(); i++) {
                items[i] = itemIds.get(i);
            }
            Arrays.sort(items);
            for (long s : items) {
                List<ZsItemReport> zsItemReports = irMap.get(s);
                List<BigDecimal> bList = new ArrayList<>();
                if (null == zsItemReports || 1 > zsItemReports.size()) {
                    bList.add(new BigDecimal("0"));
                } else {
                    bList = util.getReportLine(zsItemReports, fieldList);
                }

                rMap.put(itemService.selectZsItemById(s).getName(), bList);
            }
            mmap.put("fieldList", fieldList);
            mmap.put("list", rMap);

            //折线图
            Map<String, List<BigDecimal>> zMap = new HashMap<>();
            for (long i : items) {
                List<BigDecimal> bList = new ArrayList<>();
                List<ZsItemReport> zsItemReports = irMap.get(i);
                if (null == zsItemReports || 1 > zsItemReports.size()) {
                    for (String s : month) {
                        bList.add(new BigDecimal("0"));
                    }
                    zMap.put(itemService.selectZsItemById(i).getName(), bList);
                    continue;
                }
                Map<String, List<ZsItemReport>> collect = zsItemReports.stream().collect(Collectors.groupingBy(ZsItemReport::getMonth));
                BigDecimal[] bn = new BigDecimal[month.size()];

                for (String s : fieldList) {
                    List<BigDecimal> bnList = new ArrayList<>();
                    bnList = util.getReportZLineTwo(collect, month, s);
                    for (int i1 = 0; i1 < bnList.size(); i1++) {
                        if (null == bn[i1]) {
                            bn[i1] = new BigDecimal("0").add(bnList.get(i1));
                        } else {
                            bn[i1] = bn[i1].add(bnList.get(i1));
                        }
                    }
                }
                for (BigDecimal bigDecimal : bn) {
                    bList.add(bigDecimal);
                }
                zMap.put(itemService.selectZsItemById(i).getName(), bList);
            }
            mmap.put("zList", zMap);
        } else {
            String year = reportLineVo.getYear();
//            List<String> month = reportLineVo.getMonth();
            ZsItemReport itemReport = new ZsItemReport();
            itemReport.setItemId(itemIds.get(0));
            itemReport.setYear(year);
            itemReport.setMonthList(month);
            List<ZsItemReport> list = zsItemReportService.selectZsItemReportList(itemReport);
            ItemUtil<ZsItemReport> util = new ItemUtil<ZsItemReport>(ZsItemReport.class);
            Map<String, List<ZsItemReport>> irMap = list.stream().collect(Collectors.groupingBy(ZsItemReport::getMonth));
            List<String> fieldList = reportLineVo.getFieldList();

            //柱状图数据
//        Map<String,List<BigDecimal>> rMap=new HashMap<>();
            Map rMap = new LinkedHashMap();
            //月列表
            long[] months = new long[month.size()];
            for (int i = 0; i < month.size(); i++) {
                months[i] = Long.valueOf(month.get(i));
            }
            Arrays.sort(months);
            for (long s : months) {
                List<ZsItemReport> zsItemReports = irMap.get(s + "");
                List<BigDecimal> bList = new ArrayList<>();
                if (null == zsItemReports || 1 > zsItemReports.size()) {
                    for (String s1 : fieldList) {
                        bList.add(new BigDecimal("0"));
                    }
                } else {
                    bList = util.getReportLine(zsItemReports, fieldList);
                }
                rMap.put(s + "月", bList);
            }
            mmap.put("fieldList", fieldList);
            mmap.put("list", rMap);

            //折线图
            Map<String, List<BigDecimal>> zMap = new HashMap<>();
            for (String s : fieldList) {
                List<BigDecimal> bList = new ArrayList<>();
                bList = util.getReportZLine(irMap, month, s);
                zMap.put(s, bList);
            }
            mmap.put("zList", zMap);
        }
        return AjaxResult.success(mmap);
    }

    /**
     * 查询字段列表
     */
    @GetMapping("/fieldList")
    public Map<String, List<String>> fieldList() {
        ItemUtil<ZsItemReport> util = new ItemUtil<ZsItemReport>(ZsItemReport.class);
        Map<String, List<String>> listMap = util.getField();
        return listMap;
    }


    /**
     * 查询项目经济运行分析列表
     */
    @PreAuthorize("@ss.hasPermi('report:itemReport:list')")
    @GetMapping("/list")
    public TableDataInfo list(ZsItemReport zsItemReport) {

        SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
        if ("102".equals(sysUser.getRoleType().toString())) {
            zsItemReport.setCreateBy(SecurityUtils.getUsername());
        }
        startPage();
        List<ZsItemReport> list = zsItemReportService.selectZsItemReportList(zsItemReport);
        return getDataTable(list);
    }

    /**
     * 导出项目经济运行分析列表
     */
    @PreAuthorize("@ss.hasPermi('report:itemReport:export')")
    @Log(title = "项目经济运行分析", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ZsItemReport zsItemReport) {
        List<ZsItemReport> list = zsItemReportService.selectZsItemReportList(zsItemReport);
        ExcelUtil<ZsItemReport> util = new ExcelUtil<ZsItemReport>(ZsItemReport.class);
        return util.exportExcel(list, "项目经济运行分析数据");
    }


    @Log(title = "报表管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<ZsItemReport> util = new ExcelUtil<ZsItemReport>(ZsItemReport.class);
        List<ZsItemReport> itemReportList = util.importExcel(file.getInputStream());
        String message = zsItemReportService.importItemReport(itemReportList);
//        String operName = getUsername();
//        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }


    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<ZsItemReport> util = new ExcelUtil<ZsItemReport>(ZsItemReport.class);
        return util.importTemplateExcel("报表数据");
    }


    /**
     * 获取项目经济运行分析详细信息
     */
    @PreAuthorize("@ss.hasPermi('report:itemReport:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(zsItemReportService.selectZsItemReportById(id));
    }

    /**
     * 新增项目经济运行分析
     */
    @Log(title = "项目经济运行分析", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ZsItemReport zsItemReport) {
        return toAjax(zsItemReportService.insertZsItemReport(zsItemReport));
    }

    /**
     * 修改项目经济运行分析
     */
    @Log(title = "项目经济运行分析", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ZsItemReport zsItemReport) {
        return toAjax(zsItemReportService.updateZsItemReport(zsItemReport));
    }

    /**
     * 删除项目经济运行分析
     */
    @PreAuthorize("@ss.hasPermi('report:itemReport:remove')")
    @Log(title = "项目经济运行分析", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(zsItemReportService.deleteZsItemReportByIds(ids));
    }
}
